package com.walk.zworld.view;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener;
import com.shuyu.gsyvideoplayer.utils.CommonUtil;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.walk.zworld.R;
import com.base.lib.base.utils.ToastUtil;
import com.base.lib.log.KLog;

import moe.codeest.enviews.ENDownloadView;

public class MyGsyVideo2 extends StandardGSYVideoPlayer {

    String mCoverOriginUrl;
    ImageView thumbImage;
    private ProgressBar myBottomProgressbar;
    private SeekBar sb;
    private TextView tvSeekTime;
    private FrameLayout flSeekBar;


    public MyGsyVideo2(Context context, Boolean fullFlag) {
        super(context, fullFlag);
    }

    public MyGsyVideo2(Context context) {
        super(context);

    }

    public MyGsyVideo2(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public int getLayoutId() {
        return R.layout.you_dt_detail_control_video;
    }

    boolean isChangeSeekBar=true;

    @Override
    protected void init(Context context) {
        super.init(context);
        flSeekBar = (FrameLayout) findViewById(R.id.flSeekBar);
        sb = (SeekBar) findViewById(R.id.sb);
        tvSeekTime = (TextView) findViewById(R.id.tvSeekTime);
        thumbImage = (ImageView) findViewById(R.id.thumbImage);
        myBottomProgressbar = (ProgressBar) findViewById(R.id.bottomProgressbar);
        if (mThumbImageViewLayout != null &&
                (mCurrentState == -1 || mCurrentState == CURRENT_STATE_NORMAL || mCurrentState == CURRENT_STATE_ERROR)) {
            mThumbImageViewLayout.setVisibility(VISIBLE);
        }
        setGSYVideoProgressListener(new GSYVideoProgressListener() {
            @Override
            public void onProgress(int progress, int secProgress, int currentPosition, int duration) {
                // LogUtils.e("progress:"+progress+" secProgress:"+secProgress+" currentPosition:"+currentPosition+ " duration:"+duration);
                myBottomProgressbar.setMax(duration);
                myBottomProgressbar.setProgress(currentPosition);

                if(isChangeSeekBar) {
                    sb.setMax(duration);
                    sb.setProgress(currentPosition);
                }
            }
        });

        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser) {
                    tvSeekTime.setVisibility(VISIBLE);
                    //用户自己滑动才显示时间
                    String currentProgressTime = CommonUtil.stringForTime(seekBar.getProgress());
                    String totalTime = CommonUtil.stringForTime(seekBar.getMax());
                    tvSeekTime.setText(currentProgressTime+" / "+totalTime);
                }else {
                    tvSeekTime.setVisibility(GONE);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isChangeSeekBar=false;
                /*sb.setProgressDrawable(ResUtils.getDrawable(R.drawable.dt_video_seek_progress_press));
                sb.setMinHeight(DensityUtil.dp2px(2));
                sb.setMaxHeight(DensityUtil.dp2px(2));*/
                KLog.e("onStartTrackingTouch");

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = sb.getProgress();
                if (getGSYVideoManager() != null && mHadPlay) {
                    try {
                        //int time = seekBar.getProgress() * getDuration() / 100;
                        getGSYVideoManager().seekTo(progress);
                    } catch (Exception e) {
                        Debuger.printfWarning(e.toString());
                    }
                }
                isChangeSeekBar=true;
                tvSeekTime.setVisibility(GONE);
                /*sb.setProgressDrawable(ResUtils.getDrawable(R.drawable.dt_video_seek_progress));
                sb.setMinHeight(DensityUtil.dp2px(2));
                sb.setMaxHeight(DensityUtil.dp2px(2));*/
                KLog.e("onStopTrackingTouch");


            }
        });

        //SeekBar增加可触摸区域
        flSeekBar.setOnTouchListener((v, event) -> {
            Rect seekRect = new Rect();
            sb.getHitRect(seekRect);

            if ((event.getY() >= (seekRect.top - 500)) && (event.getY() <= (seekRect.bottom + 500))) {
                float y = seekRect.top + seekRect.height() / 2;
                //seekBar only accept relative x
                float x = event.getX() - seekRect.left;
                if (x < 0) {
                    x = 0;
                } else if (x > seekRect.width()) {
                    x = seekRect.width();
                }
                MotionEvent me = MotionEvent.obtain(event.getDownTime(), event.getEventTime(),
                        event.getAction(), x, y, event.getMetaState());
                return sb.onTouchEvent(me);
            }
            return false;
        });

    }


    @Override
    protected void changeUiToNormal() {
        KLog.e("changeUiToNormal");
        setViewShowState(mTopContainer, VISIBLE);
        setViewShowState(mBottomContainer, INVISIBLE);
        setViewShowState(mStartButton, INVISIBLE);
        setViewShowState(mLoadingProgressBar, INVISIBLE);
        setViewShowState(mThumbImageViewLayout, VISIBLE);
        setViewShowState(mBottomProgressBar, INVISIBLE);
        setViewShowState(mLockScreen, (mIfCurrentIsFullscreen && mNeedLockFull) ? VISIBLE : GONE);

        updateStartImage();
        if (mLoadingProgressBar instanceof ENDownloadView) {
            ((ENDownloadView) mLoadingProgressBar).reset();
        }
    }



    @Override
    protected void changeUiToPreparingShow() {
        KLog.e("changeUiToPreparingShow");
        setViewShowState(mTopContainer, VISIBLE);
        setViewShowState(mBottomContainer, VISIBLE);
        setViewShowState(mStartButton, INVISIBLE);
        setViewShowState(mLoadingProgressBar, VISIBLE);
        setViewShowState(mThumbImageViewLayout, VISIBLE);
        setViewShowState(mBottomProgressBar, INVISIBLE);
        setViewShowState(mLockScreen, GONE);
        if (mLoadingProgressBar instanceof ENDownloadView) {
            ENDownloadView enDownloadView = (ENDownloadView) mLoadingProgressBar;
            if (enDownloadView.getCurrentState() == ENDownloadView.STATE_PRE) {
                ((ENDownloadView) mLoadingProgressBar).start();
            }
        }

    }

    @Override
    protected void changeUiToPlayingShow() {
        KLog.e("changeUiToPlayingShow");

        setViewShowState(mTopContainer, VISIBLE);
        setViewShowState(mBottomContainer, VISIBLE);
        setViewShowState(mStartButton, INVISIBLE);
        setViewShowState(mLoadingProgressBar, INVISIBLE);
        //setViewShowState(mThumbImageViewLayout, INVISIBLE);
        setViewShowState(mBottomProgressBar, INVISIBLE);
        setViewShowState(mLockScreen, (mIfCurrentIsFullscreen && mNeedLockFull) ? VISIBLE : GONE);

        if (mLoadingProgressBar instanceof ENDownloadView) {
            ((ENDownloadView) mLoadingProgressBar).reset();
        }
        updateStartImage();
        mThumbImageViewLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                mThumbImageViewLayout.setVisibility(View.GONE);
            }
        },400);
    }

    @Override
    protected void changeUiToError() {
        KLog.e("changeUiToError");
        super.changeUiToError();
        ToastUtil.showToast("播放视频失败");
    }



    @Override
    protected void onClickUiToggle(MotionEvent e) {
        super.onClickUiToggle(e);
        clickStartIcon();
        KLog.e("onClickUiToggle："+e);
    }

    /**
     * 加载封面图url
     * @param url
     */
    public void loadCoverImage(String url) {
        mCoverOriginUrl = url;
        if(thumbImage!=null) {
            Glide.with(getContext().getApplicationContext())
                    .setDefaultRequestOptions(
                            new RequestOptions()
                                    .frame(1000000)
                                    .fitCenter())
                    .load(url)
                    .into(thumbImage);
        }
    }





    @Override
    protected void touchSurfaceMoveFullLogic(float absDeltaX, float absDeltaY) {
        super.touchSurfaceMoveFullLogic(absDeltaX, absDeltaY);
        //不给触摸快进，如果需要，屏蔽下方代码即可
        mChangePosition = false;

        //不给触摸音量，如果需要，屏蔽下方代码即可
        mChangeVolume = false;

        //不给触摸亮度，如果需要，屏蔽下方代码即可
        mBrightness = false;
    }




    @Override
    protected void touchDoubleUp(MotionEvent e) {
        //super.touchDoubleUp();
        //不需要双击暂停
    }
}
